package com.mindskip.gushuang.controller.student;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.mindskip.gushuang.base.BaseApiController;
import com.mindskip.gushuang.base.RestResponse;
import com.mindskip.gushuang.domain.AddressBean;
import com.mindskip.gushuang.domain.User;
import com.mindskip.gushuang.service.FileUpload;
import com.mindskip.gushuang.service.UserService;
import com.mindskip.gushuang.utility.RedisCache;
import com.mindskip.gushuang.webSocket.MyWsHandler;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;

import java.util.*;


@RequestMapping("/api/student/upload")
@RestController("StudentUploadController")
public class UploadController extends BaseApiController {

    private final FileUpload fileUpload;
    private final UserService userService;

    @Value("${server.port}")
    private String port;


    @Resource
    MyWsHandler myWsHandler;

    @Resource
    private RedisCache redisCache;


    @Autowired
    private AddressBean addressBean;

    @Autowired
    public UploadController(FileUpload fileUpload, UserService userService) {
        this.fileUpload = fileUpload;
        this.userService = userService;
    }

    @PostMapping("/test3")
    public RestResponse addPhoto3(@RequestBody String tableData) throws IOException, URISyntaxException {

        System.out.println("tableData  " + tableData);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(addressBean.getAddress()); // 替换为你的URL
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("category", "2");
        jsonBody.put("data", tableData);
        jsonBody.put("userId", "20220806");
        StringEntity entity = new StringEntity(jsonBody.toString(), "UTF-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json");
        HttpResponse response = httpClient.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        System.out.println(result);
        ArrayList<String> list = new ArrayList<>();
        String jsonArrayString = result;
        JSONArray jsonArray = JSON.parseObject(jsonArrayString, JSONArray.class);
        // 遍历每个JSON数组
        for (int i = 0; i < jsonArray.size(); i++) {
            // 获取当前的JSON数组
            JSONArray imagesArray = jsonArray.getJSONArray(i);

            // 遍历每个图片ID
            for (int j = 0; j < imagesArray.size(); j++) {
                // 获取图片ID字符串
                String imageId = imagesArray.getString(j);
                list.add("http://XX.XX.XX.XX:9001/ksxt/" + imageId);
            }
        }
        return RestResponse.ok(list);
    }


    @PostMapping("/test2")
    public RestResponse addPhoto2(@RequestParam(name = "file", required = false) MultipartFile file) throws FileNotFoundException, URISyntaxException {
        String imgUrl = "";
        ArrayList<String> list = new ArrayList<>();
        if (file != null) {
            try {
                UUID uuid = UUID.randomUUID();
                String s = uuid.toString();
                imgUrl = fileUpload.uploadFile(file.getInputStream(), 10, s + ".png");
                System.out.println(imgUrl);

                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpPost httpPost = new HttpPost(addressBean.getAddress()); // 替换为你的URL
                // 创建参数列表并转换为JSON对象
                JSONObject jsonBody = new JSONObject();
                jsonBody.put("imgUrl", imgUrl);
                jsonBody.put("category", "3");
                jsonBody.put("paperId", 1);
                // 将JSON对象设置为请求实体
                StringEntity entity = new StringEntity(jsonBody.toString(), "UTF-8");
                httpPost.setEntity(entity);
                // 设置请求的内容类型为application/json
                httpPost.setHeader("Content-Type", "application/json");
                // 执行请求
                HttpResponse response = httpClient.execute(httpPost);
                // 获取响应内容
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(result);
                String jsonArrayString = result;


                JSONObject jsonObject = JSON.parseObject(jsonArrayString, Feature.OrderedField);

                // 获取所有的键
                Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
                for (Map.Entry<String, Object> entry : entries) {
                    System.out.println(entry.getKey());
                    list.add(entry.getKey());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return RestResponse.ok(list);
        } else {
            // 处理文件为空的逻辑，比如返回错误信息
            return RestResponse.fail(404, "file is ull");
        }
    }


    @PostMapping("/test")
    public RestResponse addPhoto(@RequestParam(name = "file", required = false) MultipartFile file, @RequestParam(name = "userId", required = false) String userId) throws FileNotFoundException, URISyntaxException {
        System.out.println("传送过来了");
        System.out.println("userId " + userId);
        String imgUrl = "";
        if (file != null) {
            try {
                UUID uuid = UUID.randomUUID();
                String s = uuid.toString();
                imgUrl = fileUpload.uploadFile(file.getInputStream(), 10, s + ".png");
                System.out.println(imgUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String key = redisCache.getCacheObject("updateImg:" + userId);
            System.out.println("key===========" + key);
            myWsHandler.sendMessage(key, imgUrl);
            System.out.println(imgUrl);
            return RestResponse.ok(imgUrl);
        } else {
            // 处理文件为空的逻辑，比如返回错误信息
            return RestResponse.fail(404, "file is ull");
        }
    }


    @RequestMapping("/image")
    @ResponseBody
    public RestResponse questionUploadAndReadExcel(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
        long attachSize = multipartFile.getSize();
        String imgName = multipartFile.getOriginalFilename();
        try (InputStream inputStream = multipartFile.getInputStream()) {
            String filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
            userService.changePicture(getCurrentUser(), filePath);
            return RestResponse.ok(filePath);
        } catch (IOException e) {
            return RestResponse.fail(2, e.getMessage());
        }
    }


    @GetMapping("/qr")
    public RestResponse qr(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        try {
            String userId = httpServletRequest.getParameter("id");
            Map map = new HashMap<>();
            map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            map.put(EncodeHintType.CHARACTER_SET, "utf-8");
            map.put(EncodeHintType.MARGIN, 1);
            MultiFormatWriter writer = new MultiFormatWriter();
            String ip = null;
            try {
                InetAddress inetAddress = InetAddress.getLocalHost();
                ip = inetAddress.getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            //String url = "http://" + ip + ":" + port + "/pz.html?userId=" + userId;
            //System.out.println(url+" "+url);
            String url = "http://XX.XX.XX.XX:8080/pz.html?userId=" + userId;
            BitMatrix bitMatrix = writer.encode(url, BarcodeFormat.QR_CODE, 300, 300, map);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            User user = userService.getUserById(Integer.valueOf(userId));
            String imageUrl = user.getImagePath();
            if (imageUrl == null) {
                imageUrl = "http://XX.XX.XX.XX:9001/yuanfang/imgs/鱼聪明AI绘画.jpg";
            }
            HttpURLConnection conn = null;
            URL imagePath = new URL(imageUrl);
            conn = (HttpURLConnection) imagePath.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), output);
            InputStream imageInputStream = new ByteArrayInputStream(output.toByteArray());
            if (conn != null) {
                conn.disconnect();
            }

            Image logoImage = ImageIO.read(imageInputStream);
            int logoWidth = logoImage.getWidth(null);
            int logoHeight = logoImage.getHeight(null);
            if (logoWidth > 60) {
                logoWidth = 60;
            }
            if (logoHeight > 60) {
                logoHeight = 60;
            }
            Image scaledLogo = logoImage.getScaledInstance(logoWidth, logoHeight, Image.SCALE_SMOOTH);
            Graphics2D graphics = image.createGraphics();
            int x = (300 - logoWidth) / 2;
            int y = (300 - logoHeight) / 2;
            graphics.drawImage(scaledLogo, x, y, null);
            Shape shape = new RoundRectangle2D.Float(x, y, logoWidth, logoHeight, 10, 10);
            graphics.setStroke(new BasicStroke(4f));
            graphics.draw(shape);
            graphics.dispose();
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(image, "png", imOut);
            InputStream is = new ByteArrayInputStream(bs.toByteArray());
            String imgUrl = fileUpload.uploadFile(is, 10, "zzxzzzz.png");
            return RestResponse.ok(imgUrl);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResponse.fail(404, "二维码产生错误");
    }


    @PostMapping("/myqrcode/generateWithLogo")
    public void generateWithLogo(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
    ) {
        try {
            String userId = httpServletRequest.getParameter("id");
            Map map = new HashMap<>();
            map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            map.put(EncodeHintType.CHARACTER_SET, "utf-8");
            map.put(EncodeHintType.MARGIN, 1);
            MultiFormatWriter writer = new MultiFormatWriter();
            String ip = null;
            try {
                InetAddress inetAddress = InetAddress.getLocalHost();
                ip = inetAddress.getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            String url = "http://XX.XX.XX.XX:8080/pz.html?userId=" + userId;
            //String url = "http://" + ip + ":" + port + "/pz.html?userId=" + userId;
            BitMatrix bitMatrix = writer.encode(url, BarcodeFormat.QR_CODE, 300, 300, map);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            User user = userService.getUserById(Integer.valueOf(userId));
            String imageUrl = user.getImagePath();
            if (imageUrl == null) {
                imageUrl = "http://XX.XX.XX.XX:9001/yuanfang/imgs/鱼聪明AI绘画.jpg";
            }

            URL imagePath = new URL(imageUrl);
            URLConnection connection = imagePath.openConnection();
            connection.setDoInput(true); // 允许输入
            InputStream imageInputStream = connection.getInputStream();
            if (imageInputStream != null) {
                // 在这里可以对输入流进行处理，例如保存到文件、处理图片等
                System.out.println("图片输入流获取成功");
                try {
                    imageInputStream.close(); // 关闭输入流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("图片输入流获取失败");
            }

            Image logoImage = ImageIO.read(imageInputStream);
            int logoWidth = logoImage.getWidth(null);
            int logoHeight = logoImage.getHeight(null);
            if (logoWidth > 60) {
                logoWidth = 60;
            }
            if (logoHeight > 60) {
                logoHeight = 60;
            }
            Image scaledLogo = logoImage.getScaledInstance(logoWidth, logoHeight, Image.SCALE_SMOOTH);
            Graphics2D graphics = image.createGraphics();
            int x = (300 - logoWidth) / 2;
            int y = (300 - logoHeight) / 2;
            graphics.drawImage(scaledLogo, x, y, null);
            Shape shape = new RoundRectangle2D.Float(x, y, logoWidth, logoHeight, 10, 10);
            graphics.setStroke(new BasicStroke(4f));
            graphics.draw(shape);
            graphics.dispose();
            ServletOutputStream out = httpServletResponse.getOutputStream();
            ImageIO.write(image, "png", httpServletResponse.getOutputStream());
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
